<template>
  <div class="settings">
    <div class="settings-content">
      <!-- 系统设置卡片 -->
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <span>系统设置</span>
          </div>
        </template>
        <el-form label-width="100px">
          <el-form-item label="主题设置">
            <el-select v-model="currentTheme" @change="handleThemeChange">
              <el-option label="浅色主题" value="light" />
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
      <!-- 打印机设置卡片 -->
      <el-card class="settings-card">
        <template #header>
          <div class="card-header">
            <span>打印机设置</span>
          </div>
        </template>

        <!-- 小票打印机配置 -->
        <div class="printer-section">
          <h3>小票打印机</h3>
          <el-form :model="receiptPrinterConfig" label-width="120px">
            <el-form-item label="选择打印机">
              <el-select 
                v-model="receiptPrinterConfig.name" 
                placeholder="请选择打印机"
                style="width: 100%"
              >
                <el-option
                  v-for="printer in systemPrinters"
                  :key="printer.name"
                  :label="printer.name"
                  :value="printer.name"
                >
                  <span>{{ printer.name }}</span>
                  <el-tag v-if="printer.is_default" size="small" type="success">默认</el-tag>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveReceiptPrinterConfig">保存配置</el-button>
              <el-button @click="testReceiptPrinter">测试打印</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 标签打印机配置 -->
        <div class="printer-section">
          <h3>标签打印机</h3>
          <el-form :model="labelPrinterConfig" label-width="120px">
            <el-form-item label="选择打印机">
              <el-select 
                v-model="labelPrinterConfig.name" 
                placeholder="请选择打印机"
                style="width: 100%"
              >
                <el-option
                  v-for="printer in systemPrinters"
                  :key="printer.name"
                  :label="printer.name"
                  :value="printer.name"
                >
                  <span>{{ printer.name }}</span>
                  <el-tag v-if="printer.is_default" size="small" type="success">默认</el-tag>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="saveLabelPrinterConfig">保存配置</el-button>
              <el-button @click="testLabelPrinter">测试打印</el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 系统打印机列表 -->
        <div class="printer-section">
          <h3>系统打印机</h3>
          <el-table :data="systemPrinters" style="width: 100%">
            <el-table-column prop="name" label="打印机名称" />
            <el-table-column prop="is_default" label="默认打印机" width="120" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.is_default ? 'success' : ''">
                  {{ scope.row.is_default ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { printAPI } from '../api/services'
import { ElMessage } from 'element-plus'

export default {
  name: 'Settings',
  setup() {
    // 打印机配置
    const receiptPrinterConfig = ref({
      name: '',
      is_default: false
    })

    const labelPrinterConfig = ref({
      name: '',
      is_default: false
    })

    const systemPrinters = ref([])

    const PRINTER_CONFIG_KEY = 'printer_configs'

    // 保存打印机配置到本地存储
    const savePrinterConfigToLocal = (configs) => {
      localStorage.setItem(PRINTER_CONFIG_KEY, JSON.stringify(configs))
    }

    // 从本地存储加载打印机配置
    const loadPrinterConfigFromLocal = () => {
      const configStr = localStorage.getItem(PRINTER_CONFIG_KEY)
      return configStr ? JSON.parse(configStr) : null
    }

    // 修改 loadPrinterConfigs 函数
    const loadPrinterConfigs = async () => {
      try {
        // 先尝试从后端加载配置
        const configs = await printAPI.getPrinterConfigs()
        if (configs.receipt) {
          receiptPrinterConfig.value = configs.receipt
        }
        if (configs.label) {
          labelPrinterConfig.value = configs.label
        }
        
        // 保存到本地存储
        savePrinterConfigToLocal({
          receipt: receiptPrinterConfig.value,
          label: labelPrinterConfig.value
        })
      } catch (error) {
        console.error('Failed to load printer configs from backend:', error)
        
        // 如果后端加载失败，尝试从本地存储加载
        const localConfigs = loadPrinterConfigFromLocal()
        if (localConfigs) {
          if (localConfigs.receipt) {
            receiptPrinterConfig.value = localConfigs.receipt
            // 同步到后端
            try {
              await printAPI.updatePrinterConfig('receipt', localConfigs.receipt)
            } catch (e) {
              console.error('Failed to sync receipt printer config to backend:', e)
            }
          }
          if (localConfigs.label) {
            labelPrinterConfig.value = localConfigs.label
            // 同步到后端
            try {
              await printAPI.updatePrinterConfig('label', localConfigs.label)
            } catch (e) {
              console.error('Failed to sync label printer config to backend:', e)
            }
          }
        }
      }
    }

    // 加载系统打印机列表
    const loadSystemPrinters = async () => {
      try {
        systemPrinters.value = await printAPI.getSystemPrinters()
      } catch (error) {
        console.error('Failed to load system printers:', error)
        ElMessage.error('加载系统打印机列表失败')
      }
    }

    // 修改 saveReceiptPrinterConfig 函数
    const saveReceiptPrinterConfig = async () => {
      try {
        if (!receiptPrinterConfig.value.name) {
          ElMessage.warning('请选择打印机')
          return
        }
        // 验证打印机是否在系统打印机列表中
        const printerExists = systemPrinters.value.some(
          p => p.name === receiptPrinterConfig.value.name
        )
        if (!printerExists) {
          ElMessage.error('所选打印机不存在于系统中')
          return
        }
        
        // 保存到后端
        await printAPI.updatePrinterConfig('receipt', receiptPrinterConfig.value)
        
        // 保存到本地存储
        const localConfigs = loadPrinterConfigFromLocal() || {}
        localConfigs.receipt = receiptPrinterConfig.value
        savePrinterConfigToLocal(localConfigs)
        
        ElMessage.success('小票打印机配置保存成功')
      } catch (error) {
        console.error('Failed to save receipt printer config:', error)
        ElMessage.error(error.response?.data?.detail || '保存小票打印机配置失败')
      }
    }

    // 修改 saveLabelPrinterConfig 函数
    const saveLabelPrinterConfig = async () => {
      try {
        if (!labelPrinterConfig.value.name) {
          ElMessage.warning('请选择打印机')
          return
        }
        
        // 保存到后端
        await printAPI.updatePrinterConfig('label', labelPrinterConfig.value)
        
        // 保存到本地存储
        const localConfigs = loadPrinterConfigFromLocal() || {}
        localConfigs.label = labelPrinterConfig.value
        savePrinterConfigToLocal(localConfigs)
        
        ElMessage.success('标签打印机配置保存成功')
      } catch (error) {
        console.error('Failed to save label printer config:', error)
        ElMessage.error('保存标签打印机配置失败')
      }
    }

    // 测试小票打印机
    const testReceiptPrinter = async () => {
      try {
        if (!receiptPrinterConfig.value.name) {
          ElMessage.warning('请先选择并保存打印机配置')
          return
        }
        // 验证打印机是否在系统打印机列表中
        const printerExists = systemPrinters.value.some(
          p => p.name === receiptPrinterConfig.value.name
        )
        if (!printerExists) {
          ElMessage.error('所选打印机不存在于系统中')
          return
        }
        await printAPI.printReceipt({
          order_id: 0,
          room_name: "测试房间",
          start_time: new Date(),
          end_time: new Date(),
          items: [{
            snack_name: "测试商品",
            quantity: 1,
            price: 10,
            subtotal: 10
          }],
          base_amount: 100,
          snack_amount: 10,
          adjustment: 0,  // 添加 adjustment 字段
          remark: "打印机测试页",
          total_amount: 110
        })
        ElMessage.success('测试打印已发送')
      } catch (error) {
        console.error('Failed to test receipt printer:', error)
        ElMessage.error(error.response?.data?.detail || '小票打印机测试失败')
      }
    }

    // 测试标签打印机
    const testLabelPrinter = async () => {
      try {
        if (!labelPrinterConfig.value.name) {
          ElMessage.warning('请先选择并保存打印机配置')
          return
        }
        // 打印测试标签
        await printAPI.printLabel({
          name: "测试商品",
          price: 9.9
        })
        ElMessage.success('测试打印已发送')
      } catch (error) {
        console.error('Failed to test label printer:', error)
        ElMessage.error('标签打印机测试失败')
      }
    }

    onMounted(() => {
      loadPrinterConfigs()
      loadSystemPrinters()
    })

    return {
      receiptPrinterConfig,
      labelPrinterConfig,
      systemPrinters,
      saveReceiptPrinterConfig,
      saveLabelPrinterConfig,
      testReceiptPrinter,
      testLabelPrinter
    }
  }
}
</script>

<style scoped>
.settings {
  position: absolute;  /* 使用绝对定位填充整个容器 */
  top: 80px;
  bottom: 0;
  left: 200px;
  right: 0;
  padding: 15px;
  display: flex;
  flex-direction: column;
  overflow: hidden;  /* 防止双滚动条 */

}

.settings-content {
  height: 100%;
  overflow-y: auto; /* 允许内容垂直滚动 */
  padding-right: 15px; /* 为滚动条预留空间 */
}

.settings-card {
  max-width: 800px;
  margin: 0 auto 20px;
}

.printer-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.printer-section h3 {
  margin: 0 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  margin-top: 15px;
}

/* 打印机选择下拉框样式 */
:deep(.el-select-dropdown__item) {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-tag) {
  margin-left: 8px;
}

/* 自定义滚动条样式 */
.settings-content::-webkit-scrollbar {
  width: 6px;
}

.settings-content::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.settings-content::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}
</style> 